<template>
  <div class="list">
    <div class="toper" :style="is_Safari() ? { height: '140px' } : { height: '100px' }">
      <SafeTop v-show="is_Safari()" :toperMessage="topermessage" />
      <Search @search="(value: string) => {
        data.search = value;
        event.getUserList();
      }" />
      <div class="userListTable">
        <div v-for="(item, index) in navTabbar" :key="index" :class="{ 'active': judgmentAi == item.value }" @click="() => {
          judgmentAi = item.value;
          clickTable();
        }">
          {{ item.title }}
        </div>
      </div>
    </div>
    <div class="userList">
      <List ref="userList" :list="data.userList" @click="event.changeUser"
        @select-menu="(t, userId) => setUserType({ conversation_id: userId, type: t })" :receiveAi="`${judgmentAi}`" />
      <!-- 第五步 @事件名 回调过来 传过来的数据 调用API  -->
    </div>
    <div class="customerType"
      :style="is_Safari() ? { height: '70px', paddingBottom: '0px' } : { height: '80px', paddingBottom: '20px' }">
      <button v-for="(item, index) in method.lister" :key="index" @click="() => {
        method.lister.forEach(li => li.active = false);
        item.active = !item.active;
        userTable = item.value;
        userTableClick();
        gain.type = userTable
      }">
        <span class="contral" :key="index">
          <component v-if="item.active == false && item.value != userTable && typeof item.icon != 'string' && item.icon"
            :is="item.icon" />
          <!-- <component v-if="item.icon && typeof item.icon != 'string'" :is="item.icon" /> -->
          <component v-else :is="item.bicon" />
          <span class="headline">{{ item.name }}</span>
        </span>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getJargon, getMessage, getUserList, getRedDot, getUserComment, setUserType, getAiStatusSwitch } from '@/api';
import { type IData } from '@/components/user-list/interface';
import { nextTick, onBeforeMount, onBeforeUpdate, onMounted, onUnmounted, reactive, ref, shallowRef, watch, type Ref } from 'vue';
import Search from '../search/Search.vue';
import List from '../list/List.vue';
import { useRouter, useRoute } from 'vue-router';
import SafeTop from '@/toper/SafeTop.vue';
import homePage from '@/components/icon/HomePage.vue';
import followUp from '../icon/followUp.vue';
import latent from '../icon/Latent.vue';
import intention from '../icon/Intention.vue';
import deal from '../icon/Deal.vue';
import blackList from '../icon/BlackList.vue';
import inHomePage from '../icon/InHomePage.vue';
import Blatent from '../icon/Blatent.vue';
import Bintention from '../icon/Bintention.vue';
import Bdeal from '../icon/Bdeal.vue';
import './style.css'

import { getYearMonthDay } from '@/utils/date';
import { DataStorage } from '@/utils/storage';
import BblackList from '../icon/BblackList.vue';

import is_Safari from '@/utils/judgment';

// 用于传递的路由对象
const route = useRoute()
const router = useRouter()

const gain = reactive({
  type: '',
  followTime: '',
});

const topermessage = ref('会话')

let timer: any = null

const judgmentAi = ref<number>()
const userTable = ref<any>()
const clickTable = () => {
  // 方法为 存入judgnebtAi的值
  localStorage.setItem('judgmentAi', `${judgmentAi.value}`)
}

const userTableClick = () => {
  localStorage.setItem('navUserBt', `${userTable.value}`)
}

const userList = ref<InstanceType<typeof List>>();

const data: IData = reactive({
  self: {},
  search: '',
  userList: [],
  historyMessage: [],
  jargon: {},
  userComment: [],
  defaultTabbar: 0,
  userType: [
    { name: '潜在客户', value: 0 },
    { name: '意向客户', value: 1 },
    { name: '成交客户', value: 2 },
    { name: '黑名单', value: 3 },
  ],
  userNeed: {},
  getAiSwith: {}
});

document.title = '会话'

const event = {
  // 获取用户列表
  async getUserList() {
    data.userList = await getUserList({
      keyword: data.search,
      follow_time: gain.followTime,
      type: gain.type,
    });
  },
  // 获取用户评论信息
  async getUserComment() {
    const res = await getUserComment({
      to_sec_uid: data.self['to_sec_uid']
    })
    data.userComment = res
  },
  // 获取历史聊天记录
  async getHistoryMessage() {
    data.historyMessage = await getMessage({
      conversation_id: data.self['id'],
    });
  },
  // 切换用户
  async changeUser(index: number, item: Record<string, any>) {
    let identification = ''
    if (item['stranger'] == 1) {
      identification = '[M]'
    } else if (item['stranger'] == 2) {
      identification = '[Z]'
    }
    // 这是将变量传到
    const toperMessage = `${identification + ' '}` + item['to_name'] + ' · ' + item['from_name']

    DataStorage.instance.setUserListScrollTop(userListNode.value!.scrollTop);
    // console.log(item);

    // 点击取消红点
    if (item.new == 1) {
      const res: any = {}
      res['conversation_id'] = item.id
      getRedDot(res)
    }

    // 这里打印的是被点击的用户对话列表
    // console.log(item);
    data.self = item;
    data.userComment = [];

    // 每隔一段事件获取历史消息
    if (data.historyMessagePollTimer) {
      clearInterval(data.historyMessagePollTimer);
    }
    data.historyMessage = [];
    await event.getJargon();
    await event.getHistoryMessage();

    // 在浏览器中储存数据 JSON.stringify()是转字符串
    // 这里仅储存用户列表对应的id 避免数据太多而造成的卡顿
    localStorage.setItem("selfId", JSON.stringify(data.self.id))
    localStorage.setItem('self', JSON.stringify(data.self))
    localStorage.setItem('toperMessage', JSON.stringify(toperMessage))
    localStorage.setItem('selfToSecUid', data.self.to_sec_uid)
    localStorage.setItem('selfAi', data.self.ai)
    // console.log(data.self);

    // 点击切换到路由chatPage，replace表示是否以新的页面为历史页面 表示否
    router.push({ name: 'chatPage', replace: false, query: route.query })
    data.historyMessagePollTimer = setInterval(() => {
      event.getHistoryMessage();
    }, 3000);

    await event.getUserComment()
    // console.log('self', data.self);
    // console.log('userComment', data.userComment);
  },
  async Close() {
    clearTimeout(timer)
    timer = null
  },
  // 获取常用语
  async getJargon() {
    const jargon = await getJargon();
    data.jargon = {};
    jargon.forEach(item => {
      const key = item['name'] as string;
      const contents = item['info'].map(
        (ite: Record<string, string>) => ite['content']
      );
      data.jargon[key] = contents;
    });
  },
  // 第四步 父组件 引入API
  setUserType,
};



watch(
  () => [gain.type, gain.followTime],
  () => {
    data.self = {};
    data.userComment = [];
    data.historyMessage = [];
    if (userList.value) {
      userList.value.reset();
    }
    clearInterval(data.historyMessagePollTimer);
    event.getUserList();
  }
);


const userListNode = ref<HTMLElement | null>();

const method = reactive({
  lister: [
    // {
    //   value: '',
    //   active: false,
    //   // 浅层ref
    //   icon: shallowRef(homePage),
    //   name: '会话',
    // },
    // {
    //   value: '',
    //   active: false,
    //   icon: shallowRef(followUp),
    //   name: '跟进',
    // },
    {
      value: '0',
      active: false,
      icon: shallowRef(latent),
      name: '潜在',
      bicon: shallowRef(Blatent)
    },
    {
      value: '1',
      active: false,
      icon: shallowRef(intention),
      name: '意向',
      bicon: shallowRef(Bintention)
    },
    {
      value: '2',
      active: false,
      icon: shallowRef(deal),
      name: '成交',
      bicon: shallowRef(Bdeal)
    },
    {
      value: '3',
      active: false,
      icon: shallowRef(blackList),
      name: '黑单',
      bicon: shallowRef(BblackList)
    },
  ]

})

const navTabbar = [
  { title: '人工', value: 0 },
  { title: 'AI', value: 1 },
];

onMounted(async () => {
  // 在过载钩子中 获取judgmentAi的值 并且给默认值
  judgmentAi.value = Number(localStorage.getItem('judgmentAi') || '0');
  userTable.value = localStorage.getItem('navUserBt') || '0'

  gain.type = userTable.value

  await event.getUserList();
  userListNode.value = userList.value!.ulList!.firstElementChild!.childNodes[1] as HTMLElement;
  data.userListPollTimer = setInterval(async () => {
    event.getUserList()
    userListNode.value = userList.value!.ulList!.firstElementChild!.childNodes[1] as HTMLElement;
  }, 1000);
  userListNode.value.scrollTop = DataStorage.instance.getUserListScrollTop()

  // console.log(event.getAiStatusSwitch());
  // console.log(data.userList);
  is_Safari()
});


onUnmounted(() => {
  clearInterval(data.userListPollTimer);
  clearInterval(data.historyMessagePollTimer);
});
</script>
